package it.softphone.cmc.server.rest.filter;

import it.softphone.cmc.server.rest.RESTServiceAware;
import it.softphone.cmc.shared.entity.Account;
import it.softphone.cmc.shared.entity.TenantUser;
import it.softphone.commons.service.LogAware;

import javax.ws.rs.core.MultivaluedMap;


import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;

/**
 * 
 * @author bsorrentino
 *
 */
public class CMCTenantResourceFilter implements ResourceFilter,ContainerRequestFilter, LogAware {
	
	final static String[] skipTenant = {
			"scriptlet",
			"auth",
			"resources/logo"
	};
	
	/**
	 * 
	 * @param request
	 */
	@Override
	public ContainerRequest filter(ContainerRequest request) {

		final String path = request.getPath();
		
		//
		// PRECONDITIONS
		//
		if( path == null ) { 
			logger.warn( "path is null!");
			return request;
		}
		
		for( String s : skipTenant ) {
			
			//logger.debug( String.format("test path=[%s] startWith [%s]", path, s)  );
			
			if( path.startsWith(s)) {
				logger.debug( String.format("set tenant request path=[%s] skipped!", path)  );
				return request;
			}
		}

		logger.debug( String.format("request.path=[%s] processed!", path)  );

		final String tenant = request.getHeaderValue("tenant");

		try {

			
			if( tenant != null ) {
				RESTServiceAware.tenant().setTenant(tenant);
			}
			else {
				Account account = RESTServiceAware.security().getPrincipal(Account.class);
				
				TenantUser user = account.getUser();
						
				RESTServiceAware.tenant().setTenant( 
						(user==null) ? 
								RESTServiceAware.tenant().getSystemTenant() : 
									user.getTenant() );
			}
			
			
			
		} catch (Exception e) {
			logger.error( "error updating tenant !", e );
		}
		
		return request;
	}

	@Override
	public ContainerRequestFilter getRequestFilter() {
		return this;
	}

	@Override
	public ContainerResponseFilter getResponseFilter() {
		return null;
	}

}
